<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Overtrue\Wechat\Media;
use Overtrue\Wechat\Message;
use DB;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
class MediaController extends Controller
{
    private $dest = '';

    public function __construct() {
        // 保存的路径
        $this->dest = 'upload';
    }

    /**
     * 获取永久列表
     * @params $type  image video voice news
     */
    public function getMediaList(Media $media, $type='news', $offset=0, $count=20) {
        $response = $media->lists($type, $offset, $count);
        dd($response);
    }


    /**
     * 创建图片(用作图库。图文消息上传图片时可以在图库中选择)
     * @param Media $media
     * @param int $type 默认1（永久） 2 临时
     */
    public function savePic(Media $media, $type = 1) {

        $return = $this->uploadImage('file');
        $path = $return->getData()->file; // 本地上传图片路径
        if($type == 1) {
            $imageId = $media->forever()->image($path); // 上传并返回媒体ID
            // 上传图片入库记录
            DB::table('picuploads')->insert(['localurl'=>$path, 'media_id'=>$imageId['media_id'], 'weixinurl'=>$imageId['url'],'create_time'=>time() ]);
        }else {
            $imageId = $media->image($path);
        }
        $message = Message::make('image')->media($imageId);
        dd($imageId,$message);
    }

    protected function uploadImage($name) {
        $file = array('image'=>\Input::file($name));
        $rules = array('image'=>'mime:jpeg,png','image'=>'required','image'=>'image');
        $validator = \Validator::make($file, $rules);
        if($validator->fails()) {
            //return json_encode(['code'=>1000,'message'=>$validator->errors()]);
            return response()->json(['code'=>1000,'message'=>$validator->errors()->getMessages()['image'][0]]);
        }else {
            if (\Input::file($name)->isValid()) {
                $extension = \Input::file($name)->getClientOriginalExtension(); // getting image extension
                $dir = date('Ymd',time());
                if(!file_exists('upload/'.$dir)) {
                    mkdir('upload/'.$dir,0777);
                }
                $this->dest = $this->dest.'/'.$dir.'/';
                $fileName = uniqid().'.'.$extension; // renameing image
                \Request::file($name)->move($this->dest, $fileName);

                // sending back with message
                return response()->json(['code'=>2000, 'message'=>'成功上传', 'file'=>$this->dest.$fileName]);
            }
            else {
                // sending back with error message.
                return response()->json(['code'=>1001, 'message'=>'上传文件无效']);
            }
        }
    }

    /**
     * 上传图文消息
     */

    public function uploadTuwen(Media $media) {
        $article = '[{
                       "title": "标题1",
                       "thumb_media_id": "DpD-BZq-m-jS3pyEmuLB0_UicmKmPCj6I1efBa8hIHg",
                       "author": "guanyue",
                       "digest": "这里是摘要",
                       "show_cover_pic": 1,
                       "content": "这里图文消息内容，支持HTML标签",
                       "content_source_url": "http://www.yirendai.com"
                     },
                     {
                       "title": "标题2",
                       "thumb_media_id": "DpD-BZq-m-jS3pyEmuLB0_UicmKmPCj6I1efBa8hIHg",
                       "author": "guanyue",
                       "digest": "这里是摘要2",
                       "show_cover_pic": 1,
                       "content": "这里图文消息内容，支持HTML标签",
                       "content_source_url": "http://www.yirendai.com"
                     }
                    ]';

        $articles_arr = json_decode($article);
        $mediaid = $media->news($articles_arr);

        return $mediaid;

    }


    /**
     * 上传永久缩略图
     */

    public function uploadThumb() {

    }


    /**
     * 图片库列表
     * @param Media $media
     * @param int $offset
     * @param int $count
     * @return \Illuminate\View\View
     */
    public function medialist(Media $media) {
        $data = [];
        // 从本地取
        DB::setFetchMode(\PDO::FETCH_ASSOC);
        $data['mediaList']['item'] = DB::table('picuploads')->orderBy('create_time', 'desc')->paginate(12);

        //dd($data['mediaList']['item']);
        // 从线上取
        //$data['mediaList'] = $media->lists('image', $offset, $count);
        if(is_pjax()) {
            return View('admin.medialistsegment', $data);
        }

        return View('admin.medialist', $data);
    }


    /**
     * 删除图库图片
     * @param Media $media
     * @param Request $requests
     * @return \Illuminate\Http\JsonResponse
     */
    public function delPic(Media $media, Request $requests) {
        $mediaId = $requests->get('mediaId');

        // 本地删除成功之后再删线上的
        $res = DB::table('picuploads')->where('media_id', $mediaId)->delete();
        if($res) {
            $result = $media->delete($mediaId);
            if($result['errcode']==0) {
                // 删除线上图片成功
                return response()->json(['code'=>200]);
            }
        }

    }

    /**
     * 获取图片列表页面（供iframe调用）
     */
    public function getPicList() {

        $data = [];
        $data['mediaList'] = DB::table('picuploads')->orderby('create_time', 'desc')->get();

        return View('admin.getpiclist', $data);
    }

    /**
     * 输入框（供iframe调用）
     */
    public function writeWenben() {
        $data = [];

        return View('admin.writewenben', $data);
    }

    /**
     * 获取图文列表页面（供iframe调用）
     */
    public function getNewsList() {
        $data = [];
        $mediaIdList = DB::table('news')->groupby('media_id')->orderby('update_time','desc')->paginate(3);
//        dd($mediaIdList);
        foreach($mediaIdList as $key=>$value) {
            if($key == 0) {
                unset($mediaIdList['data']);
            }
            // 根据mediaid获取图文信息组装每个图文数组
            $newsInfo = $this->getNewsBymediaId($value->media_id);
            foreach($newsInfo as $k=>$newitem) {
                $mediaIdList2['data'][$key][$k]['id'] = $newitem->id;
                $mediaIdList2['data'][$key][$k]['media_id'] = $newitem->media_id;
                $mediaIdList2['data'][$key][$k]['title'] = $newitem->title;
                $mediaIdList2['data'][$key][$k]['author'] = $newitem->author;
                $mediaIdList2['data'][$key][$k]['digest'] = $newitem->digest;
                $mediaIdList2['data'][$key][$k]['content'] = $newitem->content;
                $mediaIdList2['data'][$key][$k]['content_source_url'] = $newitem->content_source_url;
                $mediaIdList2['data'][$key][$k]['thumb_media_id'] = $newitem->thumb_media_id;
                $thumb_pic = DB::table('picuploads')->where('media_id', $newitem->thumb_media_id)->lists('weixinurl');
                $mediaIdList2['data'][$key][$k]['thumb_pic'] = $thumb_pic[0];
                $mediaIdList2['data'][$key][$k]['show_cover_pic'] = $newitem->show_cover_pic;
                $mediaIdList2['data'][$key][$k]['url'] = $newitem->url;
                $mediaIdList2['data'][$key][$k]['update_time'] = $newitem->update_time;
            }
        }


        $new_data['page'] = $mediaIdList;
//        dd($mediaIdList2['data']);
        $new_data['mediaIdList'] = $mediaIdList2['data'];
        //dd($new_data['page']->hasMorePages());
        return View('admin.getnewslist', $new_data);
    }

    /**
     * 根据mediaid 获取图文信息
     * @param $mediaid
     */
    private function getNewsBymediaId($mediaid) {
        return DB::table('news')->where('media_id', $mediaid)->orderby('id', 'asc')->get();
    }

    /**
     * 同步图文消息
     * @param Media $media
     *
     */

    public function syncNews(Media $media) {
        // 先清空数据
        DB::table('news')->truncate();

        // 循环同步，一次同步20个
        $count = 20;
        $offset = 0;
        while(1==1) {
            $weixin_data = $media->lists('news', $offset, $count);
            // 同步逻辑
            if(empty($weixin_data['item'])) {
                break;
            }else {
                // 遍历图文
                foreach($weixin_data['item'] as $item) {
                    // 遍历图文内容
                    $data['media_id'] = $item['media_id'];
                    $data['update_time'] = $item['update_time'];
                    foreach($item['content']['news_item'] as $news_item) {
                        $data['title'] = $news_item['title'];
                        $data['author'] = $news_item['author'];
                        $data['digest'] = $news_item['digest']; // 摘要
                        $data['content'] = $news_item['content'];
                        $data['content_source_url'] = $news_item['content_source_url']; // 阅读原文地址
                        $data['thumb_media_id'] = $news_item['thumb_media_id']; // 缩略图media_id
                        $data['show_cover_pic'] = $news_item['show_cover_pic']; // 是否显示封面
                        $data['url'] = $news_item['url']; // 内容页地址

                        // 入库
                        DB::table('news')->insertGetId($data);
                    }

                }
                $offset = $offset + 20;
            }
        }
        return response()->json(['code'=>2000, 'message'=> '同步图文成功！']);
    }

    /**
     * 同步图片库到本地
     * @param Media $media
     */
    public function syncPic(Media $media) {
        // 先清空数据
        DB::table('picuploads')->truncate();

        //$total = $media->stats('image');
        // 循环同步，一次同步20个
        $count = 20;
        $offset = 0;
        while(1==1) {
            $weixin_data = $media->lists('image', $offset, $count);
            // 同步逻辑
            if(empty($weixin_data['item'])) {
                break;
            }else {
                // 遍历图片
                foreach($weixin_data['item'] as $item) {
                    // 遍历图片内容
                    $data['media_id'] = $item['media_id'];
                    $data['localurl'] = $item['name'];
                    $data['weixinurl'] = $item['url'];
                    $data['create_time'] = $item['update_time'];
                    // 入库
                    DB::table('picuploads')->insertGetId($data);
                }
                $offset = $offset + 20;
            }
        }
        return response()->json(['code'=>2000, 'message'=> '同步图库成功！']);
    }

    /**
     * 微信样式库
     * @return \Illuminate\View\View
     *
     */
    public function weixinStyles() {
        return View('admin.weixinstyle');
    }
}
